import React, { useState, useEffect, useRef } from 'react';
import styles from './exhibitorDetail.less';
import ExhibitorOverlay from '../../components/exhibitorOverlay';
import ExhibitorDetailSwiper from './ExhibitorDetailSwiper';
import exDefImg from '../../assets/index/exDefImg.png';
import otherIcon from '../../assets/index/other.png';
import phoenix from '../../assets/bicycleLogo/phoenix.png';
import ProductsCard from '../../components/productsCard';
import DetailBar from '../../components/detailBar';
import Enquiry from './Enquiry/enquiry';
import NewModal from '../../components/newModal';
import { useParams, useDispatch, useSelector } from 'dva';
import { GetImgs } from '../../utils/tools';
import { E } from '../../../../constants';
import { getLocale } from 'umi';
import { useIntl } from 'umi';
import defalutCoverImg from '../../assets/exhibitor/defaultCoverImg.jpg';
import IconClsoe from '../../assets/icon/close.png';
import IconShare from '../../assets/icon/ic_schb@2x.png';

import { Toast } from 'antd-mobile';

import FloatButton from '../../components/FloatButton/index';

import { getShareImage } from '../../servers/service';

function Index() {
  const { id } = useParams();
  const dispatch = useDispatch();
  const { exhibitorDetail, exProduct, userInfo } = useSelector(({ index }) => index);
  const [isShowModal, setIsShowModal] = useState(false);
  const box = useRef();
  const intl = useIntl();

  const [modalVisible, setModalVisible] = useState(false);

  const [shareVisible, setShareVisible] = useState(false);
  const [shareUrl, setShareUrl] = useState();

  const [shareParams, setShareParams] = useState();

  const barConfig = [
    {
      title: intl.formatMessage({ id: 'COLLECT' }),
      value: exhibitorDetail && exhibitorDetail.collectCount,
      callback: () => {
        if (!userInfo) {
          dispatch({
            type: 'index/setState',
            payload: {
              loginModalShow: true,
            },
          });
          return;
        }
        dispatch({
          type: 'index/apiPostLikeExhibitor',
          payload: {
            objectId: id,
            objectType: 'EXHIBITOR',
            type: 'COLLECTED',
            userId: userInfo?.user?.id,
          },
          callback: () => {
            dispatch({
              type: 'index/apiGetExhibitorDetail',
              payload: {
                id,
              },
            });
          },
        });
      },
    },
    {
      title: intl.formatMessage({ id: 'INQUIRY' }),
      callback: () => {
        if (!userInfo) {
          dispatch({
            type: 'index/setState',
            payload: {
              loginModalShow: true,
            },
          });
          return;
        }
        setIsShowModal(true);
      },
    },
  ];
  useEffect(() => {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }, []);

  useEffect(() => {
    if (id) {
      dispatch({
        type: 'index/apiGetExhibitorDetail',
        payload: {
          id,
        },
      });

      dispatch({
        type: 'index/apiGetExProducts',
        payload: { exhibitorId: id, enabled: true },
      });
    }
  }, [id]);
  useEffect(() => {
    if (exhibitorDetail) {
      const baseUrl = `${window.location.origin}/#`;

      const params = {
        boothNumber:
          exhibitorDetail.boothNumber === null ||
          exhibitorDetail.boothNumber === undefined ||
          exhibitorDetail.boothNumber === ''
            ? ''
            : exhibitorDetail.boothNumber,
        companyBannerUrl: exhibitorDetail.properties.coverImage,
        companyLogo: exhibitorDetail.properties.logo,
        companyName: getLocale() == 'zh-CN' ? exhibitorDetail.name : exhibitorDetail.nameEn,
        companyUrl: `${baseUrl}/index/exhibitorDetail/${exhibitorDetail.id}`,
        homeUrl: `${baseUrl}`,
      };

      setShareParams(
        Object.assign({}, shareParams, {
          ...params,
        }),
      );
    }
  }, [exhibitorDetail]);

  useEffect(() => {
    if (exProduct) {
      // const baseUrl = `${window.location.origin}/#`;

      const params = {
        // boothNumber: exhibitorDetail.boothNumber,
        // companyBannerUrl: exhibitorDetail.properties.shareCover,
        // companyLogo: exhibitorDetail.properties.logo,
        // companyName: getLocale() == 'zh-CN' ? exhibitorDetail.name : exhibitorDetail.nameEn,
        // companyUrl: `${baseUrl}/index/exhibitorDetail/${exhibitorDetail.id}`,
        // homeUrl: `${baseUrl}`,
        productList: [...exProduct].slice(0, 4).map((item) => ({
          productName: getLocale() == 'zh-CN' ? item.name : item.nameEn,
          productUrl: item?.properties?.albums[0],
        })),
      };

      setShareParams(
        Object.assign({}, shareParams, {
          ...params,
        }),
      );
    }
  }, [exProduct]);

  function onOver() {
    setIsShowModal(false);
  }
  function onClose() {
    setIsShowModal(false);
  }
  function getSwiperList() {
    if (exhibitorDetail) {
      if (exhibitorDetail.properties) {
        if (exhibitorDetail.properties.albums) {
          return exhibitorDetail.properties.albums;
        } else {
          return [defalutCoverImg];
        }
      } else {
        return [defalutCoverImg];
      }
    }
    return [defalutCoverImg];
  }

  const toSite = () => {
    window.open(exhibitorDetail.website);
  };

  const onShare = async () => {
    if (shareUrl) {
      setShareVisible(true);
      return;
    }
    try {
      Toast.loading('海报生成中', 0, () => {}, true);
      const baseUrl = `${window.location.origin}/#`;

      const params = {};
      const res = await getShareImage('web/share-image/company', params);
      setShareVisible(true);
      setShareUrl(res.url);
      Toast.hide();
    } catch (error) {
      Toast.hide();
    }
  };

  const onShowModal = () => {
    setModalVisible(true);
  };

  // console.log(exhibitorDetail, 'exhibitorDetail')
  // const products = new Array(3).fill('')
  const list = getSwiperList();
  return (
    <div className={styles.page}>
      <FloatButton params={shareParams} url="web/share-image/company" />
      {modalVisible && (
        <div className={styles.qrcodeModal}>
          <div className={styles.imgBox}>
            <div
              style={{
                fontSize: 18,
                fontWeight: 600,
                textAlign: 'center',
                color: 'rgba(21, 23, 41, 1)',
                marginBottom: 16,
              }}
            >
              企业微信
            </div>
            <div
              style={{
                textAlign: 'center',
              }}
            >
              <img
                src={exhibitorDetail.properties.qrcode}
                style={{
                  width: 179,
                  height: 179,
                }}
              />
            </div>
            <div className={styles.closeBox}>
              <img
                src={IconClsoe}
                className={styles.iconClose}
                onClick={() => {
                  setModalVisible(false);
                }}
              />
            </div>
          </div>
        </div>
      )}

      <>
        {shareVisible && (
          <div
            className={styles.share}
            onClick={() => {
              setShareVisible(false);
            }}
          >
            {/* <div
              className={styles.mask}
              onClick={() => {
                setShareVisible(false);
              }}
            ></div> */}
            <img src={shareUrl} className={styles.shareImage} />
            {/* <div className={styles.shareBox}>
            </div> */}
          </div>
        )}
      </>
      <ExhibitorOverlay />
      <ExhibitorDetailSwiper data={list.length > 6 ? list.slice(0, 6) : list} />

      {/* <div
        style={{
          position: 'fixed',
          zIndex: 999,
          right: 20,
          bottom: 120,
        }}
        onClick={onShare}
      >
        <img
          src={IconShare}
          style={{
            width: 65,
            height: 65,
          }}
        />
      </div> */}

      <div className={styles.info}>
        <div className={styles.areaInfo}>
          {/* <span className={styles.lable}> */}
          {/* {exhibitorDetail && exhibitorDetail.province} */}
          {/* {getLocale() == "zh-CN" ? exhibitorDetail && exhibitorDetail.province : exhibitorDetail && exhibitorDetail.provinceEn} */}
          {/* </span> */}
          <div className={styles.companyInfo}>
            <div className={styles.textBox}>
              <span className={styles.title}>
                {getLocale() == 'zh-CN'
                  ? exhibitorDetail && exhibitorDetail.name
                  : exhibitorDetail && exhibitorDetail.nameEn}
              </span>
              <span className={styles.area}>
                {/* {exhibitorDetail && exhibitorDetail.address} */}
                {getLocale() == 'zh-CN'
                  ? exhibitorDetail && exhibitorDetail.address
                  : exhibitorDetail && exhibitorDetail.addressEn}
              </span>
            </div>
            <img
              className={styles.logo}
              src={exhibitorDetail && exhibitorDetail.properties.logo}
            ></img>
          </div>
        </div>
        <div className={styles.item}>
          <div className={styles.lable}>{intl.formatMessage({ id: 'Phone' })}:</div>
          <div className={styles.text}>{exhibitorDetail && exhibitorDetail.contactNumber}</div>
        </div>
        <div className={styles.item}>
          <div className={styles.lable}>Email:</div>
          <div className={styles.text}>{exhibitorDetail && exhibitorDetail.contactEmail}</div>
        </div>
        <div className={styles.item}>
          <div className={styles.lable}>{intl.formatMessage({ id: 'Company Website' })}:</div>
          <div className={styles.text} onClick={toSite}>
            {(exhibitorDetail && exhibitorDetail.website) || ''}
          </div>
        </div>
        <div className={styles.item}>
          <div className={styles.lable}>{intl.formatMessage({ id: 'Company QRCode' })}:</div>
          <div className={styles.text}>
            {exhibitorDetail && exhibitorDetail.properties && exhibitorDetail.properties.qrcode && (
              <img
                style={{
                  width: 179,
                }}
                src={exhibitorDetail && exhibitorDetail.properties.qrcode}
                onClick={onShowModal}
              />
            )}
          </div>
        </div>
      </div>
      <div className={styles.otherProducts}>
        <div className={styles.iconBox}>
          <img src={otherIcon} className={styles.otherIcon}></img>
          <span>{intl.formatMessage({ id: 'MISCELLANEOUS_PRODUCTS' })}</span>
        </div>
        <div className={styles.productsBox} ref={box}>
          {exProduct &&
            exProduct.map((item, index) => {
              return <ProductsCard obj={item} key={index} />;
            })}
          {exProduct && exProduct.length % 2 != 0 && <div className={styles.emptyLabel}></div>}
        </div>
      </div>
      <DetailBar barConfig={barConfig} />
      <NewModal
        showModal={isShowModal}
        // onClose={onClose}
      >
        <Enquiry type="1" exhibitorID={id} onOver={onOver} onClose={onClose} />
      </NewModal>
    </div>
  );
}

export default Index;
